// pages/category/category.js
Page({
  data: {
    active:0,
    menuList: [{
        name: "热门菜品"
      },
      {
        name: "家常菜"
      },
      {
        name: "早餐"
      },
      {
        name: "午餐"
      },
      {
        name: "晚餐"
      },
      {
        name: "川菜"
      },
      {
        name: "湘菜"
      },
      {
        name: "粤菜"
      },
      {
        name: "其他"
      },
    ],
    activeIndex: 0, // 当前选中的菜单索引
    subActiveIndex: 0, // 当前选中的二级分类索引
    contentList: [], // 全部数据
    filteredContentList: [], // 筛选后的数据
  },

  onLoad() {
    // 初始化加载数据
    this.loadContent();
  },

  // 切换左边菜单
  switchMenu(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeIndex: index
    });
    this.filterContent();
  },

  // 切换二级分类
  switchSubMenu(e) {
    const index = +e.currentTarget.dataset.index; // 获取点击的索引
    this.setData({
      subActiveIndex: index // 更新当前选中的索引
    });
    this.filterContent(); // 可能需要根据新的索引筛选内容
  },

  // 加载数据
  loadContent() {
    // 模拟从后端获取数据
    const fakeData = this.getFakeData();
    this.setData({
      contentList: fakeData
    });
    this.filterContent();
  },

  // 筛选数据
  filterContent() {
    const {
      contentList,
      activeIndex,
      subActiveIndex
    } = this.data;
    const mainCategory = this.data.menuList[activeIndex].name; // 主分类
    const subCategory = ["全部", "主食", "汤类"][subActiveIndex]; // 二级分类

    // 筛选逻辑
    let filteredData = contentList.filter((item) => {
      if (subCategory === "全部") {
        return item.mainCategory === mainCategory;
      } else {
        return item.mainCategory === mainCategory && item.subCategory === subCategory;
      }
    });

    this.setData({
      filteredContentList: filteredData
    });
  },

  // 生成假数据
  getFakeData() {
    const fakeData = [];
    const mainCategories = ["热门菜品","家常菜", "早餐", "午餐", "晚餐", "川菜", "湘菜", "粤菜", "其他"];
    const subCategories = ["全部", "主食", "汤类"];

    for (let i = 0; i < 50; i++) {
      const mainCategory = mainCategories[Math.floor(Math.random() * mainCategories.length)];
      const subCategory = subCategories[Math.floor(Math.random() * subCategories.length)];

      fakeData.push({
        id: i + 1,
        image: `/images/recipe${i + 1}.jpg`,
        name: `菜品 ${i + 1}`,
        mainCategory: mainCategory,
        subCategory: subCategory,
      });
    }

    return fakeData;
  },
  // Tabs切换事件处理函数
  onTabChange(event) {
    this.setData({
      active: event.detail
    });
    // 根据切换的tab索引，请求相应的菜品数据并更新页面
    console.log('切换到tab:', event.detail);
  }
});